﻿using Identity_JWT_WebAPI.Register.JWT;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace Identity_JWT_WebAPI
{
    /// <summary>
    /// 注册JWT
    /// </summary>
    public static class RegisterJWT
    {
        public static WebApplicationBuilder AddJWT(this WebApplicationBuilder builder)
        {
           IConfigurationSection cofSection = builder.Configuration.GetSection("JWT");
            IServiceCollection services = builder.Services;
            services.Configure<JWTOptions>(cofSection);
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(j =>
            {
                var jwtOpt = cofSection.Get<JWTOptions>();
                byte[] keyBytes = Encoding.UTF8.GetBytes(jwtOpt.SigningKey);
                var secKey = new SymmetricSecurityKey(keyBytes);
                j.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = false,  //验证发行人
                    ValidIssuer = jwtOpt.Issuer, //发行人
                    ValidateAudience = false,  //验证接收者
                    ValidAudience = jwtOpt.Audience, //订阅者
                    ValidateLifetime = true,  //验证生命周期
                    ValidateIssuerSigningKey = true,  //验证发行人的签名Key
                    ClockSkew = TimeSpan.FromSeconds(300), //过期时间容错值，解决服务器端时间不同步问题（秒）
                    RequireExpirationTime = true, //要求到期时间

                    IssuerSigningKey = secKey
                };
            });
            return builder;
        }
    }
}
